package com.study.client.paho;


import com.study.client.common.constant.MqttQos;
import com.study.client.common.constant.SubscribeTopicConstant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * 模拟一个客户端接收消息
 * @author peter.wang
 */
@Slf4j
@Data
public class ClientMQTT {

    private MqttConnectOptions options;

    private MqttClient client;

    public static MqttClient publicClient;


    /*** @Title: createClientMQTT
     * @Description:模拟一个client MQTT端
     * @Params  serverURI,mqttUserName,mqttPassword,clientId
     * @Returns org.eclipse.paho.client.mqttv3.MqttClient
     * @author WangZhongming
     * @version 1.0
     * @since  2022/9/21 13:51
     */
    public static MqttClient createClientMQTT(String serverURI, String mqttUserName, String mqttPassword, String clientId) throws MqttException {

        serverURI = "tcp://" + serverURI;
        MqttClient client = new MqttClient(serverURI, clientId, new MemoryPersistence());
        // MQTT的连接设置
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，设置为true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(true);
        // 设置连接的用户名
        options.setUserName(mqttUserName);
        // 设置连接的密码
        options.setPassword(mqttPassword.toCharArray());
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(20);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(20);
        options.setMaxInflight(1000);
        //this.options = options;
        //this.client = client;
        // 设置回调
        client.setCallback(new SubscribeCallback(client));
        client.connect(options);
        client.subscribe(SubscribeTopicConstant.subscribeTopic, MqttQos.QOS1);
        client.subscribe(SubscribeTopicConstant.newDeviceSubscribeTopic, MqttQos.QOS1);
        publicClient = client;
        return client;
    }

}

